/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package modules.enderecamento.models.dao;

/**
 *
 * @author Clezio
 */
import java.util.List;
import modules.enderecamento.models.dto.Fornecedor;
import modules.enderecamento.util.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.exception.ConstraintViolationException;
   
 public class FornecedorDAO{  
     
     private SessionFactory sessionFactory;
     
     public FornecedorDAO() throws Exception{
         sessionFactory = HibernateUtil.getSessionFactory();
     }
       
     public void save(Fornecedor fornecedor) throws Exception{
         Session session = sessionFactory.openSession();
         Transaction tx = session.beginTransaction();
         if(fornecedor.getId() > 0){
            session.update(fornecedor);
         }else{
            session.save(fornecedor);
         }
         session.flush();
         tx.commit();
         session.close();  
     }  
       
     public java.util.List<Fornecedor> getList(String condicao) throws Exception{
         Session session = sessionFactory.openSession();
         Query query = session.createQuery(condicao);
         List fornecedors = query.list();
         session.flush();  
         session.close();  
         return fornecedors;
     }  
       
     public Fornecedor retrieve(Integer pk) throws Exception{
         Session session = sessionFactory.openSession();
         Fornecedor fornecedor = (Fornecedor)session.load(Fornecedor.class, pk);
         Fornecedor fornecedorDTO = mountDto(fornecedor);
         session.flush();
         session.close();  
         return fornecedorDTO;
     }  
       
     public void delete(Fornecedor fornecedor) throws Exception{
         Session session = sessionFactory.openSession();
         Transaction tx = session.beginTransaction();
         session.delete(fornecedor);
         session.flush();
         tx.commit();
         session.close();  
     }

    public Fornecedor mountDto(Fornecedor fornecedor) {
        Fornecedor fornecedorDTO = new Fornecedor();
        fornecedorDTO.setId(fornecedor.getId());
        fornecedorDTO.setNome(fornecedor.getNome());
        fornecedorDTO.setCnpj(fornecedor.getCnpj());
        fornecedorDTO.setProdutoses(fornecedor.getProdutoses());
        fornecedorDTO.setAtivo(fornecedor.isAtivo());
        return fornecedorDTO;
    }
 }